﻿using ServiceCore.Entity;
using ServiceCore.Entity.Const;
using ServiceCore.Utility.Extension;
using ServiceCore.WebApi.Controllers;
using StaticVar = ServiceCore.Utility.StaticVar;

namespace ServiceCore.WebApi.jwt
{
    /// <summary>
    /// jwt刷新token服务（JWT不能直接注销，本功能用于注销）
    /// </summary>
    public static class JwtUserFileService
    {
        private static string FileDirectory = LogServiceCore.LogServiceCore_Log + StaticVar.PathSplitLine + "登录用户";

        /// <summary>
        /// 创建一个token
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string CreateRefreshToken(JwtUserInfo user)
        {
            user.RefreshToken = Guid.NewGuid().ToString();
            var json = user.ToJson();
            json.LogWriteTxtSingle(user.Id.ToString());

            return user.RefreshToken;
        }

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string GetRefreshToken(string userId)
        {
            var json = LogGetTxtSingle(userId);
            if (string.IsNullOrEmpty(json))
                return "";
            JwtUserInfo user = json.ToObject<JwtUserInfo>();
            if (user.IsNull() || user.Id == 0)
                return "";

            return user.RefreshToken;
        }

        /// <summary>
        /// 获取缓存用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static JwtUserInfo GetCacheUsers(string userId)
        {
            JwtUserInfo user = null;

            var json = LogGetTxtSingle(userId);
            if (string.IsNullOrEmpty(json))
                return user;
            user = json.ToObject<JwtUserInfo>();
            return user;
        }

        /// <summary>
        /// 删除token
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static void RevokeRefreshToken(string userId)
        {
            "{}".LogWriteTxtSingle(userId, true);
        }

        /// <summary>
        /// 单文件写入
        /// </summary>
        /// <param name="logContext">要写入的内容</param>
        /// <param name="path">路径</param>
        /// <param name="filename">文件名</param>
        public static void LogWriteTxtSingle(this string logContext, string filename, bool isDelete = false)
        {
            if (string.IsNullOrEmpty(logContext))
                return;
            var dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine + FileDirectory + StaticVar.PathSplitLine;
            if (Directory.Exists(dirBase) == false)
                Directory.CreateDirectory(dirBase);
            filename = dirBase + filename + ".txt";
            if (isDelete)
            {
                if (File.Exists(filename))
                    File.Delete(filename);
            }
            else
            {
                UtilityFunction.LockExtension(() =>
                {
                    File.WriteAllText(filename, logContext);
                });
            }
        }

        /// <summary>
        /// 单文件写入
        /// </summary>
        /// <param name="logContext">要写入的内容</param>
        /// <param name="path">路径</param>
        /// <param name="filename">文件名</param>
        public static string LogGetTxtSingle(string filename)
        {
            string content = string.Empty;

            var dirBase = StaticVar.HttpPath + StaticVar.PathSplitLine + FileDirectory + StaticVar.PathSplitLine;
            if (Directory.Exists(dirBase) == false)
                Directory.CreateDirectory(dirBase);
            filename = dirBase + filename + ".txt";
            if (File.Exists(filename))
            {
                content = File.ReadAllText(filename);
            }

            return content;
        }
    }
}
